<?php

namespace App\Http\Controllers;

use App\Http\Requests\IndexAdminRequest;
use App\Http\Requests\StoreAdminRequest;
use App\Http\Requests\UpdateAdminRequest;
use App\Http\Resources\AdminResource;
use App\Models\Admin;
use App\Models\Dic;
use App\Rules\PhoneRule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

use Illuminate\Validation\Rule;

class AdminController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }
    /**
     * Display a listing of the resource.
     */
    public function index(IndexAdminRequest $request, Admin $admin)
    {
        $status = $request->query('status');
        $query = Admin::query();
        // 如果不是超级管理员，则限制只能查看自己的信息
        // if (!isSuperadmin()) {
        //     $query->where('admin_id', Auth::id());
        // }
        // 根据 $keywords 和 $status 添加动态查询条件
        if ($request->filled('keywords') && $request->query('keywords')) {
            $keywords = $request->query('keywords');
            $query->where(function ($q) use ($keywords) {
                $q->where('username', 'like', "%$keywords%")
                    ->orWhere('phone', 'like', "%$keywords%");
                // 添加其他需要查询的字段
            });
        }
        if ($request->filled('status') && $request->query('status')) {
            $query->where('status', $status);
        }
        $data = $query->with(['roles', 'statuslabel', 'admins'])->paginate(
            $request->query('pageSize'),
            ['*'],
            'page',
            $request->query('pageNum')
        );
        $response = AdminResource::collection($data);
        $total = $response->total(); // 获取分页信息中的总数
        return $this->success('查询成功', $response, $total);
    }

    /**
     * 我的推广（查询我的下级）
     *
     * @return 
     */
    public function myextend(Request $request)
    {
        Validator::make($request->input(), [
            'pageNum' => ['required'],
            'pageSize' => ['required'],
        ])->validate();

        $admin = Admin::where('admin_id', Auth::id());
        $admin->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where('name', 'like', "%$name%");
        });
        $data = $admin->select(['id', 'username', 'avatar', 'phone', 'promotion_revenue', 'created_at'])
            ->paginate(
                $request->query('pageSize'),
                ['*'],
                'page',
                $request->query('pageNum')
            );
        $response = AdminResource::collection($data);
        $total = $response->total(); // 获取分页信息中的总数
        return $this->success('查询成功', $response, $total);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreAdminRequest $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Admin $admin)
    {
        $this->authorize('view', $admin);
        return $this->success('查询成功', new AdminResource($admin->load(['roles', 'statuslabel', 'admins'])));
    }

    /**
     * 修改用户信息
     *
     * @param Request $request
     * @param Admin $admin
     * @return 
     */
    public function updateinfo(Request $request, Admin $admin)
    {
        $validatedData = Validator::make($request->input(), [
            'email' => ['required', 'email'],
            'username' => ['required', 'regex:/^[a-z0-9]+$/', Rule::unique('admins')->ignore(Auth::id())],
            'phone' => ['required', new PhoneRule()],
            'avatar' => ['required'],
        ])->validate();
        // 只更新验证通过的字段  
        $admin = $admin->findOrFail(Auth::id());
        $admin->update($validatedData);
        return $this->success('更新成功', $admin);
    }

    /**
     * 只能超级管理员操作
     * Update the specified resource in storage.
     */
    public function update(UpdateAdminRequest $request, Admin $admin)
    {
        $this->authorize('update', $admin);
        $admin->fill($request->input());
        $admin->save();
        return $this->success('用户更改成功', $admin);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Admin $admin)
    {
        //
    }
}
